import axios from 'axios'
import router from '@/router'
import { Message, MessageBox } from 'element-ui'

// let urlPrefix = 'https://lequ.yowow.cn'
let urlPrefix = 'http://localhost:20266'
// let urlPrefix = 'https://ice.yowow.cn'

axios.defaults.baseURL = urlPrefix

axios.defaults.timeout = 120000

axios.interceptors.request.use(config => {
  // 拦截请求
  var storage = window.localStorage
  var token = storage.getItem('token')
  var admin = storage.getItem('admin')
  if (token && admin) {
    config.headers.Authorization = token
    config.headers.Admin = admin
  } else {
    router.replace({ name: 'login' })
  }
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(function (response) {
  return response
}, function (error) {
  if (error.response) {
    switch (error.response.status) {
      case 401:
        var storage = window.localStorage
        storage.removeItem('admin')
        storage.removeItem('token')
        MessageBox.confirm('是否立刻重新登录？', '登录已超时', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          router.replace({ name: 'login' })
        }).catch(() => {
          Message.error('请重新登录，否则无法继续操作')
        })
        break
      default:
        console.info(error)
        Message.error(error.response)
    }
  }
  return Promise.reject(error)
})

export default axios

export const errhandler = err => {
  if (err instanceof Error) {
    Message.error({
      message: err.message
    })
  } else {
    Message.error({
      message: err.status
    })
  }
}

export const domain = urlPrefix
